var _index = 1;
layui.config({
    base: "static/layui/module/"
}).extend({
    dynamicCondition: 'dynamicCondition/dynamicCondition'
}).use(['form','layer','jquery','table','laydate','upload','dynamicCondition'],function() {
    var form = layui.form,
        layer = layui.layer,
        laypage = layui.laypage,
        $ = layui.jquery,
        table = layui.table,
        upload = layui.upload,
        laydate = layui.laydate
    dynamicCondition=layui.dynamicCondition;

    table.render({
        elem:'#constantTable'
        ,title:'表常量列表'
        ,url:'/manage/common_data_dictionary_and_set/constant_list'
        ,method:'post'
        ,height: 'full-60'
        ,page: true //开启分页
        ,limit: 10
        ,limits: [10,15,18,20,30,40,50]
        ,loading: true
        ,cols: [[ //表头
            {type:'radio'}
            ,{field: 'url', title: '表名'}
            ,{field: 'name', title: '描述'}
        ]]
        ,text: {
            none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
        }
        ,toolbar:'#constantTableToolbar'
        ,defaultToolbar: ['']
    });

    var dataFields = [
        {field:"url", title:"表名", edit:"text"}
        ,{field:"name", title:"描述", edit:"text"}
    ];

    var dc = dynamicCondition.create({
        fields:dataFields
        ,tableId:"constantTable"
        ,conditionTextId:"#findMsg"
        ,type:"complex"
        ,requestDataType:"json"
        ,counts:10
        ,queryCallBack:function(requestData){
        }
    });

    //单击行选中radio及加载permission信息
    table.on('row(constantTable)', function(obj){
        obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');//选中行样式
        obj.tr.find('input[lay-type="layTableRadio"]').prop("checked",true);
        form.render('radio');
        reloadField(obj.data.id);
    });

    table.on('toolbar(constantTable)', function(obj){
        var tableCheckData = table.checkStatus(obj.config.id);
        switch(obj.event){
            case 'find':
                dc.open();
                break;
        };
    });

    function reloadField(constantId){
        var height=(Number($(".layui-fluid").height()))-50; // 计算高度
        $('#fieldTable').datagrid({
            url:'/manage/common_data_dictionary_and_set/table_field_list/'+constantId,
            height: height,
            columns:[[
                {field: 'ck', checkbox: true}
                ,{field:'tableKey',title:'主键',width:100}
                ,{field:'tableField',title:'字段',width:100}
                ,{field:'fieldExplain',title:'字段描述',width:100}
                ,{field:'fieldType',title:'字段类型',width:100}
                ,{field:'numericScal',title:'小数位数',width:100,align:'right'}
                ,{field:'entityField',title:'对象属性',width:100}
                ,{field:'defaultShow',title:'默认显示',editor:{type:'combobox',
                        options:{
                            valueField: 'label',
                            textField: 'value',
                            data: [{
                                label: '是',
                                value: '是'
                            },{
                                label: '否',
                                value: '否'
                            }]
                        }},width:100}
                ,{field:'queryCriteria',title:'是否查询条件',editor:{type:'combobox',
                        options:{
                            valueField: 'label',
                            textField: 'value',
                            data: [{
                                label: '是',
                                value: '是'
                            },{
                                label: '否',
                                value: '否'
                            }]
                        }},width:100}
                ,{field:'queryCriteriaType',title:'条件类型',editor:{
                        type:'combobox',
                        options:{
                            valueField: 'label',
                            textField: 'value',
                            url:'/manage/common_data_dictionary_and_set/query_type_list',
                            onLoadSuccess: function(data){
                                for(var i in data){
                                    data[i].index = _index;
                                }
                                _index++;
                                return data;
                            },
                            onClick: function(rec){
                                var enumList = $('#fieldTable').datagrid('getEditor', {index:rec.index,field:'enumList'});
                                if(rec.label == '枚举下拉框'){
                                    $(enumList.target).textbox({required:true});
                                }else{
                                    $(enumList.target).textbox({required:false});
                                }
                            }
                        }},width:100}
                ,{field:'enumList',title:'枚举（label-value格式;间隔）',editor:{type:'textbox'},width:200}
                ,{field:'sort',title:'排序方式',editor:{type:'combobox',
                        options:{
                            valueField: 'label',
                            textField: 'value',
                            data: [{
                                label: '',
                                value: '不参与排序'
                            },{
                                label: '是',
                                value: '升序'
                            },{
                                label: '否',
                                value: '降序'
                            }]
                        }},width:100}
                ,{field:'uniqueness',title:'是否防重',editor:{type:'combobox',
                        options:{
                            valueField: 'label',
                            textField: 'value',
                            data: [{
                                label: '是',
                                value: '是'
                            },{
                                label: '否',
                                value: '否'
                            }]
                        }},width:100}
                ,{field:'disable',title:'是否为禁用字段',editor:{type:'combobox',
                        options:{
                            valueField: 'label',
                            textField: 'value',
                            data: [{
                                label: '是',
                                value: '是'
                            },{
                                label: '否',
                                value: '否'
                            }]
                        }},width:100}
                ,{field:'required',title:'是否必填',editor:{type:'combobox',
                        options:{
                            valueField: 'label',
                            textField: 'value',
                            data: [{
                                label: '是',
                                value: '是'
                            },{
                                label: '否',
                                value: '否'
                            }]
                        }},width:100}
                ,{field:'defaultValue',title:'默认值（不需要表单新增）',editor:{
                        type:'combobox',
                        options:{
                            valueField: 'label',
                            textField: 'value',
                            url:'/manage/common_data_dictionary_and_set/default_value_list'
                        }},width:100}
            ]],
            toolbar:[{
                text:'重新加载',
                iconCls:'icon-reload',
                handler:function(){
                    var shadeIndex = top.layer.msg('重新加载中，请稍候',{icon: 16,time:false,shade:0.4});
                    $.post("/manage/common_data_dictionary_and_set/refresh",{id: constantId},function(d){
                        if(d.code == '200'){
                            layer.msg("重载成功",{icon:1});
                            $('#fieldTable').datagrid('reload')
                        }else{
                            layer.msg("重载失败,"+d.msg,{icon:2});
                        }
                        top.layer.close(shadeIndex);
                    })
                }
            },'-',{
                text:'编辑',
                iconCls:'icon-edit',
                handler:function(){
                    var rows = $('#fieldTable').datagrid('getRows');
                    $.each(rows,function(index,e){
                        $('#fieldTable').datagrid('beginEdit',index+1);
                    });
                }
            },'-',{
                text:'提交编辑',
                iconCls:'icon-ok',
                handler:function(){
                    var rows = $('#fieldTable').datagrid('getRows');
                    var disable_count = 0;
                    for(var i in rows){
                        var vali = $('#fieldTable').datagrid('validateRow', i);
                        if(!vali){
                            alert("请完善信息");
                            return;
                        }
                    }
                    for(var i in rows){
                        if(rows[i].queryCriteriaType == '联表下拉框'){
                            if(rows[i].queryConstantId == null || rows[i].queryConstantId == ''){
                                alert(rows[i].fieldExplain+"字段条件类型为联表下拉框，请先进行联表转译设置");
                                return;
                            }
                        }
                    }
                    for(var i in rows){
                        $('#fieldTable').datagrid('endEdit', i);
                        if(rows[i].disable == 'true'){
                            disable_count++;
                        }
                        rows[i].defaultShow = rows[i].defaultShow=='是'?true:false;
                        rows[i].queryCriteria = rows[i].queryCriteria=='是'?true:false;
                        rows[i].uniqueness = rows[i].uniqueness=='是'?true:false;
                        rows[i].disable = rows[i].disable=='是'?true:false;
                        rows[i].required = rows[i].required=='是'?true:false;
                        rows[i].sort = rows[i].sort=='是'?true:rows[i].sort=='否'?false:'';
                    }
                    if(disable_count > 1){
                        alert("禁用字段最多只能有一个");
                        return;
                    }

                    _index = 1;
                    var shadeIndex = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.4});
                    $.post("/manage/common_data_dictionary_and_set/save_set",{info: JSON.stringify(rows)},function(d){
                        if(d.code == '200'){
                            layer.msg("操作成功",{icon:1});
                            $('#fieldTable').datagrid('reload')
                        }else{
                            layer.msg("操作失败,"+d.msg,{icon:2});
                        }
                        top.layer.close(shadeIndex);
                    })
                }
            },'-',{
                text:'联表转译设置',
                iconCls:'icon-save',
                handler:function(){
                    var rows = $('#fieldTable').datagrid('getSelections');
                    if(rows.length != 1){
                        layer.msg("请选择一条要联表转译的数据",{icon:2});
                        return;
                    }
                    if(rows[0].tableKey != '' && rows[0].tableKey != null){
                        layer.msg("表主键不支持联表转译",{icon:2});
                        return;
                    }
                    var index = layer.open({
                        type: 2
                        ,title: '联表转译设置'
                        ,area: ['80%', '100%']
                        ,content: '/manage/common_data_dictionary_and_set/setHtml/'+rows[0].id+'/'+constantId
                        ,btn: ['保存', '取消']
                        ,yes: function(index, layero){
                            var iframeWindow = $(layero).find("iframe")[0].contentWindow;
                            var data = iframeWindow.backData();
                            var shadeIndex = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.4});
                            $.post("/manage/common_data_dictionary_and_set/save_query_table",{id:rows[0].id,constantId:data.constantId,associatedFiled:data.associatedFiled,fields:JSON.stringify(data.fields)},function(d){
                                if(d.code=='200'){
                                    top.layer.alert("设置成功",{icon:1});
                                    $('#fieldTable').datagrid('reload')
                                }else{
                                    top.layer.msg("设置失败,"+d.msg,{icon:2});
                                }
                                top.layer.close(shadeIndex);
                                layer.close(index);
                            },"json")
                        }
                    });
                }
            }]
        })
        $('#fieldTable').datagrid("options").view.onBeforeRender = function (target, rows) {
            $.each(rows, function (index, e){
                e.defaultShow = e.defaultShow?'是':'否';
                e.queryCriteria = e.queryCriteria?'是':'否';
                e.uniqueness = e.uniqueness?'是':'否';
                e.disable = e.disable?'是':'否';
                e.required = e.required?'是':'否';
                e.sort = e.sort==null?'':e.sort?'是':'否';
            })
        };
    }
})